package com.aiowang.springboot.dynamic.activemq.listener;

import com.aiowang.springboot.dynamic.activemq.interfaces.DynamicActiveMQTransportListener;
import com.aiowang.springboot.dynamic.activemq.utils.DynamicActiveMQApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.transport.TransportListener;

import java.io.IOException;
import java.util.Map;




/**
 *
 *  消息传输监听
 * @author aiowang
 */
@Slf4j
public class ActiveMQTransportListener implements TransportListener {


    /**
     * 服务名
     */
    private String activeMQSeverName;

    private static Map<String, DynamicActiveMQTransportListener> dynamicActiveMQTransportListenerMap;


    /**
     * 构造函数
     */
    public ActiveMQTransportListener(){}

    /**
     * 含参构造函数
     * @param activeMQSeverName 服务名
     */
    public ActiveMQTransportListener(String activeMQSeverName){
        this.activeMQSeverName = activeMQSeverName;
    }

    /**
     * 对消息传输命令进行监控
     * @param object  object
     */
    @Override
    public void onCommand(Object object) {
        log.debug("{} -> onCommand -> {}...",activeMQSeverName,object);
        checkInitDynamicActiveMQTransportListenerMap();
        for(DynamicActiveMQTransportListener mapValue : dynamicActiveMQTransportListenerMap.values()){
            mapValue.onCommand(object, activeMQSeverName);
        }
    }

    /**
     * 对监控到的异常进行触发
     * @param error error
     */
    @Override
    public void onException(IOException error) {
        log.error("{} -> onException -> 消息服务器连接错误......{}",activeMQSeverName,error);
        checkInitDynamicActiveMQTransportListenerMap();
        for(DynamicActiveMQTransportListener mapValue : dynamicActiveMQTransportListenerMap.values()){
            mapValue.onException(error, activeMQSeverName);
        }
    }

    /**
     * 当failover时触发
     */
    @Override
    public void transportInterupted() {
        log.warn("{} -> transportInterupted -> 消息服务器连接发生中断...",activeMQSeverName);
        checkInitDynamicActiveMQTransportListenerMap();
        for(DynamicActiveMQTransportListener mapValue : dynamicActiveMQTransportListenerMap.values()){
            mapValue.transportInterupted(activeMQSeverName);
        }
    }

    /**
     * 监控到failover恢复后进行触发
     */
    @Override
    public void transportResumed() {
        log.info("{} -> transportResumed -> 消息服务器连接已恢复...",activeMQSeverName);
        checkInitDynamicActiveMQTransportListenerMap();
        for(DynamicActiveMQTransportListener mapValue : dynamicActiveMQTransportListenerMap.values()){
            mapValue.transportResumed(activeMQSeverName);
        }
    }

    /**
     * 检查dynamicActiveMQTransportListenerMap，若无值则初始化
     */
    private void checkInitDynamicActiveMQTransportListenerMap(){
        if(dynamicActiveMQTransportListenerMap == null){
            dynamicActiveMQTransportListenerMap = DynamicActiveMQApplicationContextUtils.getDynamicActiveMQTransportListenerImpls();
        }
    }
}
